//
//  NetWorkTools.swift
//  MyWeiBo
//
//  Created by mac on 15/3/3.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit
//import SimpleNetWork
//import JSONModel

// MARK: 最顶层的网络访问类
class NetWorkTools: NSObject {
    
    // MARK: 创建表格
    override class func initialize() {
        SQLite3Tool.shareInstance.openDataBase("MyWeiBo.db")
    }
    
    class func requestJSONFromURLString(urlString: String, method: HTTPMethod, params: [String : AnyObject]?, complete: Complete){
        SimpleNetWork.shareInstance.requestJSON(urlString, method, params, complete)
    }
}

// OAuth访问工具类
typealias OAuthComplete = (account: Account?, error: NSError?) -> ()
class OAuthNetWorkTools: NetWorkTools {
    static let TOKEN_URI = "https://api.weibo.com/oauth2/access_token"
    class func requestAccountWithOAuthRequest(request: OAuthRequest, complete: OAuthComplete){
        let params: [String: String] = request.dictionaryFromSelf() as! [String: String]
        self.requestJSONFromURLString(TOKEN_URI, method: .POST, params: params) { (result, error) -> () in
            if error == nil {
                let r: AnyObject? = Account.objectWithDictionary(result as! [String: AnyObject])
                let account: Account = r as! Account
                complete(account: account, error: error)
                return
            }
            complete(account:nil, error: error)
        }
    }
}

// MARK: 操作微博数据
class StatusTool: NetWorkTools {
    
    override class func initialize() {
        // 图片信息表
        createPictureTable()
        // 用户信息表
        createUserInfoTable()
        // 微博数据缓存表
        createStatusTable()
    }
    
    static let STATUS_URI = "https://api.weibo.com/2/statuses/home_timeline.json"
    static let SEND_STATUS_URI = "https://api.weibo.com/2/statuses/update.json"
    /// 加载最新的数据
    class func requestStatusWithStatusRequest(request: StatusRequest, complete: ((statues: Statuses?, error: NSError?) -> ())) {
        let params = request.dictionaryFromSelf()
        self.requestJSONFromURLString(STATUS_URI, method: .GET, params: params) { (result, error) -> () in
            var statues: Statuses?
            if result != nil {
                statues = Statuses.objectWithDictionary(result as! [String :AnyObject]) as? Statuses
                if let statuesArray = statues!.statuses {
                    for status in statuesArray {
                        if !status.insert() {
                            println("保存数据失败 --")
                            break
                        }
                    }
                }
            }
            complete(statues: statues, error: error)
        }
    }
    
    ///  发布一条微博
    ///
    ///  :param: text     微博的正文
    ///  :param: complete 发布完成的回调 , 如果返回的错误跟结果都是空就说明 token 已经过期了
    class func sendStatusWithStatusText(text: String, complete: ((result: AnyObject?, error: NSError?) -> ())) {
        if let account = AccountTool.getAccountFromLoacl() {
            var params = [String: AnyObject]()
            params["status"] = text
            params["access_token"] = account.access_token
            self.requestJSONFromURLString(SEND_STATUS_URI, method: .POST, params: params) { (result, error) -> () in
                complete(result: result, error: error)
            }
        } else {
            complete(result: nil, error: nil)
        }
    }
}

extension StatusTool {
    
    class func createPictureTable() {
        let sql = "CREATE TABLE IF NOT EXISTS \(StatusPictureURL.TABLENAME) ( \n" +
        "id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" +
        "thumbnail_pic text NOT NULL DEFAULT '', \n" +
        "status_id integer NOT NULL DEFAULT 0 \n" +
        ")"
        if SQLite3Tool.shareInstance.execSQL(sql) {
            println("创建 PictureTable 表成功")
        } else {
            println("创建 PictureTable 表失败")
        }
    }
    
    class func createUserInfoTable() {
        let sql = "CREATE TABLE IF NOT EXISTS \(UserInfo.TABLENAME) ( \n" +
        "id INTEGER NOT NULL, \n" +
        "screen_name TEXT NOT NULL DEFAULT '', \n" +
        "name TEXT, \n" +
        "profile_image_url TEXT NOT NULL DEFAULT '', \n" +
        "avatar_large TEXT DEFAULT '', \n" +
        "gender TEXT NOT NULL DEFAULT 'n', \n" +
        "followers_count INTEGER NOT NULL DEFAULT 0, \n" +
        "friends_count INTEGER NOT NULL DEFAULT 0, \n" +
        "statuses_count INTEGER NOT NULL DEFAULT 0, \n" +
        "favourites_count INTEGER NOT NULL DEFAULT 0, \n" +
        "created_at TEXT NOT NULL DEFAULT '', \n" +
        "verified INTEGER NOT NULL DEFAULT 0, \n" +
        "verified_type INTEGER NOT NULL DEFAULT -1, \n" +
        "mbrank INTEGER NOT NULL DEFAULT 0, \n" +
        "PRIMARY KEY(id) \n" +
        ")"
        
        if SQLite3Tool.shareInstance.execSQL(sql) {
            println("创建 UserInfo 表成功")
        } else {
            println("创建 UserInfo 表失败")
        }
    }
    
    class func createStatusTable() {
        let sql = "CREATE TABLE IF NOT EXISTS \(Status.TABLENAME) ( \n" +
        "id INTEGER NOT NULL, \n" +
        "text TEXT NOT NULL DEFAULT '', \n" +
        "source TEXT NOT NULL DEFAULT '', \n" +
        "retweeted_status_id INTEGER NOT NULL DEFAULT 0, \n" +
        "reposts_count INTEGER NOT NULL DEFAULT 0, \n" +
        "comments_count INTEGER NOT NULL DEFAULT 0, \n" +
        "attitudes_count INTEGER NOT NULL DEFAULT 0, \n" +
        "user_id INTEGER NOT NULL DEFAULT 0, \n" +
        "created_at TEXT NOT NULL DEFAULT '', \n" +
        "refresh_flag INTEGER NOT NULL DEFAULT 0,\n" +
        "PRIMARY KEY(id) \n" +
        ")"
        
        if SQLite3Tool.shareInstance.execSQL(sql) {
            println("创建 StatusTable 表成功")
        } else {
            println("创建 StatusTable 表失败")
        }
    }
    
}

